#!/bin/bash
#
# Simple terraform variable documenter
#
set -e
sourceDir="$(cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
belowDir=$(echo "${sourceDir}" | sed -e 's/\/scripts*$//g')
export belowDir

if [[ ${OSTYPE} =~ ^darwin* ]]; then
	export tfDoc="terraform-docs-darwin"
elif [[ ${OSTYPE} =~ ^linux-gnu* ]]; then
	export tfDoc="terraform-docs"
else
	echo "Cannot identify OS...exiting"
	exit 1
fi

[[ ! -x ${belowDir}/bin/${tfDoc} ]] && { echo -e "This script requires terraform-docs available from <https://github.com/segmentio/terraform-docs>....exiting"; exit 1; }

if [ "$#" -ne 1 ]; then
	echo "Usage: $0 <base-directory>"
	echo "e.g $0 ../terraform"
	exit 1
fi

directory=$1
readmeName="README-auto.md"

# shellcheck disable=SC2156
find "${directory}" -type d -not -path "${directory}/.git/*" -not -path "${directory}/.terraform/*" -exec bash -c '${belowDir}/bin/${tfDoc} md "{}"  >  "{}"/README-auto.md;' \;

find "${directory}" -name "${readmeName}" -size 1c -type f -delete

# shellcheck disable=SC1117
printf "\n\033[35;1mUpdating the following READMEs with terraform-docs\033[0m\n\n"

find "${directory}" -name "${readmeName}"

